﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.Dto.Check;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class CheckController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CheckController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取检查单列表
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetChecks")]
        public GetChecksResponse GetChecks(int cardId, string startDate)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.Id == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetChecksResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }

            var request = new GetExamInfoRequest();
            request.CardNo = card.PatientId;
            //request.ItemType = "D";
            //request.BeginDate = startDate.ToDateTimeOrDefault().ToString("yyyy-MM-dd");
            //request.EndDate = startDate.ToDateTimeOrDefault().AddDays(15).ToString("yyyy-MM-dd");

            GetExamInfoResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetExamInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetExamInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取检查单列表Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetChecksResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取检查单列表超时"
                };
            }

            if (response.ResultCode != "0")
            {
                return new GetChecksResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            List<GetChecksResponse.Check> examInfoList = new List<GetChecksResponse.Check>();
            foreach (var examInfo in response.ExamList)
            {
                var exam = new GetChecksResponse.Check
                {
                    Id = examInfo.ExamID,
                    Name = examInfo.ExamName,
                    //Date = examInfo.ExamDate,
                    //CardNo = examInfo.CardNo,
                    //PatientName = examInfo.PatientName,
                    //PatientSex = examInfo.PatientSex,
                    Status = examInfo.Status
                };

                examInfoList.Add(exam);

                //if (!_ctx.MedExams.Any(x => x.ExamNo == examInfo.ExamID))
                //{
                //    _ctx.MedExams.Add(new MedExam
                //    {
                //        WxUserId = azUser.UserId,
                //        CardType = card.CardType.ToInt32().ToString(),
                //        CardNo = card.CardNo,
                //        ExamDate = examInfo.ExamDate,
                //        ExamNo = examInfo.ExamID,
                //        ExamName = examInfo.ExamName,
                //        PatientName = examInfo.PatientName,
                //        PatientSex = examInfo.PatientSex,
                //        PatientId = examInfo.PatientID,
                //        ExamStatus = examInfo.Status
                //    });
                //}
            }
            //_ctx.SaveChanges();

            return new GetChecksResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                IsInp = "0",
                Checks = examInfoList.OrderBy(x => x.Status).ThenByDescending(x => x.Id).ToList()
            };
        }

        /// <summary>
        /// 获取检查单详情
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="appNo"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetCheckDetail")]
        public GetCheckDetailResponse GetCheckDetail(int cardId, string appNo)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.Id == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetCheckDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }
            var request = new InpGetExamDetailRequest();
            request.CardNo = card.CardNo;
            request.ExamId = appNo;
            request.ItemType = "D";

            InpGetExamDetailResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetExamDetail", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<InpGetExamDetailResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取住院检查单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetCheckDetailResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取检查单详情超时"
                };
            }

            if (response.ResultCode != "0")
            {
                return new GetCheckDetailResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            return new GetCheckDetailResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                CheckItems = response.ExamItemList.Select(x => new GetCheckDetailResponse.CheckItem
                {
                    ItemNo = x.ItemNo,
                    ItemDate = x.ItemDate,
                    //Prompt = x.Prompt,
                    //Content = x.Content,
                    //todo 比标准版本多出来的字段，前端页面摆放
                    ExamItemName = x.ExamItemName,
                    LabItemName = x.LabItemName,
                    //LabRepItemNo = x.LabRepItemNo,
                    LabRepResult = x.LabRepResult,
                    LabRepUnits = x.LabRepUnits,
                    LabInd = x.LabInd,
                    LabContext = x.LabContext
                }).ToList()
            };
        }

    }
}
